<template>
    <div>
      <el-tag
        :key="tag"
        v-for="tag in dynamicTags"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)" v-if="tag.length">
        {{tag}}
      </el-tag>
      <el-input
        class="input-new-tag"
        v-if="inputVisible"
        v-model="inputValue"
        ref="saveTagInput"
        size="small"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
      >
      </el-input>
      <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新增</el-button>
    </div>
</template>
<script>
import _ from "lodash";
export default {
  props: {
    value: {
      type: String
    },
    separator: {
      type: String,
      default: ","
    }
  },
  created() {
    if (this.value.length) {
      this.dynamicTags = this.value.split(this.separator);
    }
    this.$watch("value", val => {
      this.dynamicTags = val.split(this.separator);
    });
    this.$watch("dynamicTags", val => {
      console.log(val);
    });
  },
  mounted() {},
  data() {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: ""
    };
  },
  methods: {
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      this.updateValue();
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
        this.updateValue();
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    updateValue() {
      const tmp = _.cloneDeep(this.dynamicTags);
      if (tmp.length) {
        this.$emit("input", tmp.join(this.separator));
      } else {
        this.$emit("input", "");
      }
    }
  },
  computed: {},
  components: {}
};
</script>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
